<template>
  <div class="container">
    <el-row>
      <el-col>
        <el-input
          :value="listQuery.memberId"
          :placeholder="$t('please_input_member_id')"
          maxlength="18"
          size="small"
          class="width-180"
          clearable
          @input="value => listQuery.memberId = value.replace(/[^\d]/g,'')" />
        <el-input v-model="listQuery.nickName" :placeholder="$t('please_enter_member_nickname')" size="small" class="width-180" clearable />
        <el-input
          :value="listQuery.tel"
          :placeholder="$t('please_input_mobile_phone_number')"
          maxlength="11"
          size="small"
          class="width-180"
          clearable
          @input="value => listQuery.tel = value.replace(/[^\d]/g,'')" />
        <el-date-picker
          v-model="datePicker"
          :start-placeholder="$t('el.datepicker.startDate')"
          :end-placeholder="$t('el.datepicker.endDate')"
          type="daterange"
          range-separator="~"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
          @change="dateChange"/>
        <el-input :value="listQuery.masterId" :placeholder="$t('please_enter_the_master_member_id')" maxlength="18" size="small" class="width-180" clearable @input="value => listQuery.masterId = value.replace(/[^\d]/g,'')" />
        <el-input-number v-model="listQuery.childLevel" :min="1" :max="10" :placeholder="$t('query_level')" size="small" class="width-180"/>
        <el-select v-model="listQuery.riskStatus" class="w-140" size="small">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-col>
      <el-col class="p-t-5">
        <el-select v-model="listQuery.numberType" class="w-140" size="small" @change="numberTypeChange">
          <el-option v-for="item in valueOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-input :placeholder="$t('min_value')" :disabled="listQuery.numberType==null" :maxlength="maxLength" :value="listQuery.minNumber" clearable size="small" class="width-180" @input="value => listQuery.minNumber = value.replace(/[^\d]/g,'')" /> --
        <el-input :placeholder="$t('max_value')" :disabled="listQuery.numberType==null" :maxlength="maxLength" :value="listQuery.maxNumber" clearable size="small" class="width-180" @input="value => listQuery.maxNumber = value.replace(/[^\d]/g,'')" />
        <el-input v-model="listQuery.device" :placeholder="$t('device_no')" size="small" class="width-180" clearable />
        <el-input v-model="listQuery.mac" :placeholder="$t('mac_address')" size="small" class="width-180" clearable />
        <el-button type="primary" icon="el-icon-search" size="small" @click="search()">{{ $t('search') }}</el-button>
        <el-tooltip
          :content="$t('remaining_balance_total_balance_remaining_coins')"
          class="item"
          effect="dark"
          placement="bottom-start"
        >
          <i class="el-icon-warning-outline"/>
        </el-tooltip>
        <el-button v-if="hasExportAuth" :disabled="exportLoading" :loading="exportLoading" type="primary" size="small" @click="toExport()">{{ $t('export_doc') }}</el-button>
      </el-col>
    </el-row>

    <p class="tip"> {{ $t('this_page_does_not_search_by_default') }} </p>
    <el-tabs v-model="activeName" type="card" class="p-t-15">
      <el-tab-pane :label="$t('common_data')" name="tidy">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          element-loading-text="Loading"
          border
          fit
          class="table-box"
          highlight-current-row
          style="width: 100%;margin-top:15px;"
          @sort-change="sortChange">
          <el-table-column :label="$t('serial_number')" width="60" align="center">
            <template slot-scope="scope">
              <span>
                {{ (listQuery.index - 1) * listQuery.size + scope.$index +1 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('member_id')" align="center" width="70" prop="id"/>
          <el-table-column :label="$t('member_nickname')" align="center" prop="nickName" />
          <el-table-column :label="$t('we_media_user_type')" >
            <template slot-scope="{row}">
              <span> {{ mediaTypeMap[row.mediaType]}} </span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('phone_number')" align="center" prop="mobile"/>
          <el-table-column :label="$t('connected_referral_number')" align="center" sortable="custom" prop="childCount">
            <template slot-scope="{row}">
              {{ row.childCount }} <br>
              <el-button v-if="row.childCount>0" type="primary" size="mini" @click="goUserDetail('?masterId=' + row.id + '&childLevel=1')">{{ $t('details') }}</el-button>
            </template>
          </el-table-column>
          <el-table-column :label="$t('registered_time')" align="center" prop="registerTime" width="100"/>
          <el-table-column :label="$t('current_mac_address')" align="center" width="150">
            <template slot-scope="{row}">
              <div v-for="(item, index) in row.macs" :key="item">
                <span>{{ item }}</span> <br>
                <span>({{ row.macCounts[index] }})</span> <br>
                <el-button type="primary" size="mini" @click="goUserDetail('?mac=' + item)">{{ $t('details') }}</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('device_id')" align="center" width="200">
            <template slot-scope="{row}">
              <div v-for="(item, index) in row.devices" :key="item">
                <span>{{ item }}</span> <br>
                <span>({{ row.deviceCounts[index] }})</span> <br>
                <el-button type="primary" size="mini" @click="goUserDetail('?device=' + item)">{{ $t('details') }}</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('member_status_change_times')" >
            <template slot-scope="{row}">
              <span> {{ row.statusChangeCount }} </span>
              <el-button type="primary" size="mini" @click="checkHistory(row.id)"> >></el-button>
            </template>
          </el-table-column>

          <el-table-column :label="$t('status')" width="120" align="center">
            <template slot-scope="{row}">
              <state-change :row="row" @changeStatusSuccee="getList" :pageName="pageName" :isShowWhite="true"/>
            </template>
          </el-table-column>

          <el-table-column :label="$t('operation')" align="center" width="120">
            <template slot-scope="scope">
              <el-button type="primary" plain size="mini" @click="goDetail(scope.row.id)">{{ $t('member_details') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane :label="$t('all_data')" name="all">
          <el-table
            v-loading="listLoading"
            :data="tableData"
            element-loading-text="Loading"
            border
            fit
            class="table-box"
            highlight-current-row
            style="width: 100%;margin-top:15px;"
            @sort-change="sortChange">
            <el-table-column :label="$t('serial_number')" width="60" align="center">
              <template slot-scope="scope">
                <span>
                  {{ (listQuery.index - 1) * listQuery.size + scope.$index +1 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('member_id')" align="center" width="70" prop="id"/>
            <el-table-column :label="$t('member_nickname')" align="center" prop="nickName" />
            <el-table-column :label="$t('we_media_user_type')" >
              <template slot-scope="{row}">
                <span> {{ mediaTypeMap[row.mediaType]}} </span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('phone_number')" align="center" prop="mobile"/>
            <el-table-column :label="$t('remaining_balance') + '($)'" align="center" sortable="custom" prop="smallMoney" width="70"/>
            <el-table-column :label="$t('total_accumulated_balance') + '($)'" align="center" sortable="custom" prop="totalMoney"/>
            <el-table-column :label="$t('remaining_coins')" align="center" sortable="custom" prop="smallCoin"/>
            <el-table-column :label="$t('total_accumulated_coins')" align="center" sortable="custom" prop="totalCoin"/>
            <el-table-column :label="$t('connected_referral_number')" align="center" sortable="custom" prop="childCount">
              <template slot-scope="{row}">
                {{ row.childCount }} <br>
                <el-button v-if="row.childCount>0" type="primary" size="mini" @click="goUserDetail('?masterId=' + row.id + '&childLevel=1')">{{ $t('details') }}</el-button>
              </template>
            </el-table-column>
            <el-table-column :label="$t('registered_time')" align="center" prop="registerTime" width="100"/>
            <el-table-column :label="$t('last_active_time')" align="center" prop="lastActiveTime" width="100"/>
            <el-table-column :label="$t('current_mac_address')" align="center" width="150">
              <template slot-scope="{row}">
                <div v-for="(item, index) in row.macs" :key="item">
                  <span>{{ item }}</span> <br>
                  <span>({{ row.macCounts[index] }})</span> <br>
                  <el-button type="primary" size="mini" @click="goUserDetail('?mac=' + item)">{{ $t('details') }}</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('device_id')" align="center" width="200">
              <template slot-scope="{row}">
                <div v-for="(item, index) in row.devices" :key="item">
                  <span>{{ item }}</span> <br>
                  <span>({{ row.deviceCounts[index] }})</span> <br>
                  <el-button type="primary" size="mini" @click="goUserDetail('?device=' + item)">{{ $t('details') }}</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('trigger_rules')" >
              <template slot-scope="scope" >
                <span :title="scope.row.allRules">
                  {{ scope.row.firstRuleGroupName }} {{ scope.row.ruleGroupNameList.length>1?"...":'' }}
                </span>
              </template>
            </el-table-column>

            <el-table-column :label="$t('member_status_change_times')" >
              <template slot-scope="{row}">
                <span> {{ row.statusChangeCount }} </span>
                <el-button type="primary" size="mini" @click="checkHistory(row.id)"> >></el-button>
              </template>
            </el-table-column>

            <el-table-column :label="$t('status')" width="120" align="center">
              <template slot-scope="{row}">
                <state-change :row="row" @changeStatusSuccee="getList" :pageName="pageName" :isShowWhite="true"/>
              </template>
            </el-table-column>

            <el-table-column :label="$t('operation')" align="center" width="120">
              <template slot-scope="scope">
                <el-button type="primary" plain size="mini" @click="goDetail(scope.row.id)">{{ $t('member_details') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 分页 -->
    <el-row style="text-align:right;">
      <Pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.index"
        :limit.sync="listQuery.size"
        @pagination="getList" />
    </el-row>

    <!-- 状态变更次数 -->
    <state-change-history :show.sync="show.history" :listData="historyData" />
  </div>
</template>
<script>
import { getMemberList } from '@/api/user-exception-filtering/abnormal-behavior';
import { changeStatusJS, watchRouterJs } from './../mixins/common.js';
import { getChangeRecordsApi } from '@/api/user-exception-filtering/releaseProcessing.js';
import StateChangeHistory from '@/views/member-exception-filtering/components/StateChangeHistory.vue';
import StateChange from '@/views/member-exception-filtering/components/StateChange.vue';
import Pagination from '@/components/Pagination';
import { getNav } from '@/api/menu';
import { getToken } from '@/utils/auth';

const maxLength = 8;

export default {
  name: 'MemberQuery',
 
  mixins: [changeStatusJS, watchRouterJs],

  components: {
    StateChange,
    StateChangeHistory,
    Pagination
  },

  data() {
    return {
      maxLength,
      activeName: 'tidy',
      pageName: '会员异常筛选 / 会员查询',
      mediaTypeMap: {
        1: this.$t('none_self_media_users'),
        2: this.$t('general_self_media_users'),
        3: this.$t('big_v_self_media_users')
      },
      memberTypeDic: {
        GREY: this.$t('grey_list'),
        BLACK: this.$t('black_list'),
        NOTSURE: this.$t('suspicious_situation'),
        NORMAL: this.$t('normal')
      },
      noSureTypeDic: {
        GREY: this.$t('grey_list'),
        BLACK: this.$t('black_list'),
        NOTSURE: this.$t('suspicious_situation'),
        NORMAL: this.$t('normal'),
        WHITE: this.$t('white_list')
      },
      tableData: [],
      historyData: [],
      total: 0,
      listLoading: false,
      datePicker: [],
      listQuery: {
        memberId: '',
        nickName: '',
        tel: '',
        beginTime: '',
        endTime: '',
        index: 1,
        size: 20,
        numberType: null, // 数值类型 1、零钱余额；2、零钱总额；3、金币余额；4、金币总额；5、徒弟数量
        minNumber: null,
        maxNumber: null,
        device: null,
        mac: null,
        ip: null,
        sortBy: 8, // 排序字段，1、会员id；2、零钱余额；3、零钱总额；4、金币余额；5、金币总额；6、关联徒弟数量；7、注册时间；8、最后活跃时
        orderBy: 'desc',
        masterId: null,
        childLevel: 5,
        riskStatus: null
      },
      show: {
        history: false,
      },
      hasExportAuth: false, // 默认没有导出权限
      exportLoading: false,
      exportQuery: {},
      statusOptions: [{
        label: this.$t('membership_status'),
        value: null
      }, {
        label: this.$t('normal'),
        value: 1
      }, {
        label: this.$t('suspicious_situation'),
        value: 2
      }, {
        label: this.$t('grey_list'),
        value: 3
      }, {
        label: this.$t('black_list'),
        value: 4
      }],
      valueOptions: [{
        label: this.$t('select_value'),
        value: null
      }, {
        label: this.$t('remaining_balance'),
        value: 1
      }, {
        label: this.$t('total_balance'),
        value: 2
      }, {
        label: this.$t('remaining_coins'),
        value: 3
      }, {
        label: this.$t('total_coins'),
        value: 4
      }, {
        label: this.$t('number_of_referrals'),
        value: 5
      }]
    };
  },

  created() {
    // 查询层级默认5层
    const { memberId, device, mac, ip, masterId, childLevel = 5 } = this.$route.query;
    const { listQuery } = this;
    this.listQuery = { ...listQuery, device, mac, ip, masterId, childLevel, memberId };
    this.checkExportAuth();

    // 有查询参数自动搜索
    if (Object.keys(this.$route.query).length > 0) {
      this.search();
    }
  },

  methods: {
    async checkExportAuth() {
      const { code, data } = await getNav();
      if (code == 200) {
        this.hasExportAuth = !!(data && data.permission.includes('member_export'));
      }
    },

    async getList() {
      this.listLoading = true;
      try {
        this.exportQuery = { ...this.listQuery };
        const { code, data, count } = await getMemberList(this.listQuery);
        this.listLoading = false;
        if (code == 200) {
          const tableData = data.map(item => {
            item.ruleGroupNameList = item.ruleGroupNameList;
            item.updateTime =
                item.updateTime === undefined
                  ? ''
                  : item.updateTime.split('T').join(' ');
            return item;
          });
          this.tableData = this.formatRule(
            JSON.parse(JSON.stringify(tableData))
          );
          this.total = count || 0;
        }
      // eslint-disable-next-line no-empty
      } catch (e) {
      }
    },

    async checkHistory(memberId) {
      try {
        const { code, data, msg } = await getChangeRecordsApi({ memberId });
        if (code == 200) {
          this.historyData = this.formatRule(
            JSON.parse(JSON.stringify(data || []))
          );
          this.show.history = true;
        } else {
          this.$message.warning(msg);
        }
      } catch (e) {
        this.$message.warning(this.$t('there_was_an_error_in_the_request'));
      }
    },

    // 规则格式化
    formatRule(data) {
      const rule = data.map(item => {
        item.firstRuleGroupName = '';
        item.allRules = '';
        const rule = item.ruleGroupNameList;
        rule.forEach((ruleItem, index) => {
          if (
            !ruleItem.frequency && !ruleItem.operator && !ruleItem.periodOfTime
          ) {
            if (index == 0) {
              item.firstRuleGroupName = ruleItem.ruleName;
            } else {
              ruleItem.ruleName = ruleItem.ruleName + ';';
            }
            item.allRules += ruleItem.ruleName;
          } else {
            let all = '';
            if (ruleItem.operator == '') {
              all = `${ruleItem.ruleName} ${ruleItem.periodOfTime}${
                ruleItem.frequency
              }`;
            } else {
              all = `${ruleItem.ruleName} ${ruleItem.periodOfTime}${
                ruleItem.frequency
              }${ruleItem.operator}${ruleItem.value}`;
            }

            if (index == 0) {
              item.firstRuleGroupName = all;
            }
            item.allRules += `${all} ; `;
          }
        });
        return item;
      });
      return rule;
    },

    search() {
      const { maxNumber, minNumber } = this.listQuery;
      if (minNumber && maxNumber && (Number(minNumber) > Number(maxNumber))) {
        this.$message.warning(this.$t('the_minimum_value_cannot_be_greater_than_the_maximum_value'));
        return;
      }

      const beginTime = this.datePicker && this.datePicker[0] || null;
      const endTime = this.datePicker && this.datePicker[1] || null;
      const index = 1;
      this.listQuery = { ... this.listQuery, beginTime, endTime, index };
      this.getList();
    },

    sortChange({ column, prop, order }) {
      const propMap = {
        smallMoney: 2,
        totalMoney: 3,
        smallCoin: 4,
        totalCoin: 5,
        childCount: 6
      };
      const sortBy = propMap[prop];
      const orderBy = order == 'ascending' ? 'asc' : 'desc';
      const index = 1;
      this.listQuery = { ... this.listQuery, sortBy, orderBy, index };
      this.getList();
    },

    numberTypeChange(val) {
      if (val === null) {
        this.listQuery.maxNumber = null;
        this.listQuery.minNumber = null;
      }
    },

    // 导出结果保存和上次列表搜索结果一致
    toExport() {
      const that = this;
      if (that.exportLoading) return;
      that.exportLoading = true;
      const language = that.$store.state.app.language || 'zh';
      const lanMap = {
        zh: 'zh-Hans',
        en: 'en-US',
        km: 'km-KH'
      };
      const lan = lanMap[language];

      var xhh = new XMLHttpRequest();
      xhh.open('post', process.env.BASE_API + '/v1/member/exportMember');
      xhh.setRequestHeader('X-Token', getToken());
      xhh.setRequestHeader('lan', lan);
      xhh.setRequestHeader('content-type', 'application/json;charset=UTF-8');
      xhh.responseType = 'blob';
      xhh.onreadystatechange = function() {
        if (xhh.readyState === 4 && xhh.status !== 200) {
          that.$message.warning('导出出错');
          that.exportLoading = false;
        }
        if (xhh.readyState === 4 && xhh.status === 200) {
          var blob = new Blob([xhh.response]);
          var csvUrl = URL.createObjectURL(blob);
          var link = document.createElement('a');
          var fileName = xhh
            .getResponseHeader('Content-Disposition')
            .split(';')[1]
            .split('fileName=')[1];
          var fileNameUnicode = xhh
            .getResponseHeader('Content-Disposition')
            .split('fileName*=')[1];
          if (fileNameUnicode) {
            fileName = decodeURIComponent(fileNameUnicode.split("''")[1]);
          }

          document.body.appendChild(link);
          link.href = csvUrl;
          link.target = '_blank';
          link.id = 'linkId';
          link.className = 'linkId';
          link.download = decodeURI(fileName);
          document.getElementById('linkId').click();
          link.remove();
          that.exportLoading = false;
        }
      };
      const query = { ...this.exportQuery, index: 1, size: 30000 };
      xhh.send(JSON.stringify(query));
    },

    // 打开一个新的当前页
    goUserDetail(query) {
      const url = `${process.env.DATA_ADMIN}/#/userExceptionFiltering/memberQuery${query}`;
      window.open(url);
    },

    goDetail(memberId) {
      const url = `${process.env.DATA_ADMIN}/#/userExceptionFilter/userDetail?memberId=${memberId}`;
      window.open(url);
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
  height: calc(100vh-50px);
  overflow-y: auto;
}
.text-align--right {
  text-align: right;
}
.width {
  &-180 {
    width: 180px;
  }
}

.p-t-5 {
  padding-top: 5px;
}

.container /deep/ th {
  div {
    word-break: break-word;
  }
}

.container /deep/ .table-box {
  .el-table__row .cell{
    max-height: 600px;
    overflow-y: auto;
  }
}

.tip {
  padding-top: 15px;
  font-size: 16px;
  line-height: 2;
}
</style>
